package format

import (
	"github.com/pion/rtp"
	"gogs.smarteye.com/smarteye/gortc/pkg/format/rtpfile"
)

// File is a file RTP format.
type File struct {
	PayloadTyp uint8
	// 传递文件信息(设备id,文件时间,经纬度等) 格式为 key=value, 多个用逗号隔开

	FileID       string
	FileJsonInfo string

	FileOffset int64
}

// Init computes the clock rate of the format. It is mandatory to call it.
func (f *File) Init() error {
	return nil
}

func (f *File) unmarshal(ctx *unmarshalContext) error {
	f.PayloadTyp = ctx.payloadType

	for key, val := range ctx.fmtp {
		switch key {
		case "file-json-info":
			f.FileJsonInfo = val
		case "file-id":
			f.FileID = val
		}
	}

	return nil
}

// Codec implements Format.
func (f *File) Codec() string {
	return "FILE"
}

// ClockRate implements Format.
func (f *File) ClockRate() int {
	return 90000
}

// PayloadType implements Format.
func (f *File) PayloadType() uint8 {
	return f.PayloadTyp
}

// RTPMap implements Format.
func (f *File) RTPMap() string {
	return "FILE/90000"
}

// FMTP implements Format.
func (f *File) FMTP() map[string]string {
	var result = map[string]string{}
	if len(f.FileJsonInfo) > 0 {
		result["file-json-info"] = f.FileJsonInfo
	}
	if len(f.FileID) > 0 {
		result["file-id"] = f.FileID
	}

	return result
}

// PTSEqualsDTS implements Format.
func (f *File) PTSEqualsDTS(*rtp.Packet) bool {
	return true
}

func (f *File) CreateDecoder() (*rtpfile.Decoder, error) {
	d := &rtpfile.Decoder{}

	err := d.Init()
	if err != nil {
		return nil, err
	}

	return d, nil
}

// CreateEncoder creates an encoder able to encode the content of the format.
func (f *File) CreateEncoder() (*rtpfile.Encoder, error) {
	sequenceNumber := uint16(0)

	e := &rtpfile.Encoder{
		PayloadType:           f.PayloadTyp,
		InitialSequenceNumber: &sequenceNumber,
	}

	err := e.Init()
	if err != nil {
		return nil, err
	}

	return e, nil
}
